package com.example.doer.reading.AppActivities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.example.doer.reading.AppDataModel.AppUser;
import com.example.doer.reading.R;
import com.example.doer.reading.global.MyApplication;
import com.mob.MobSDK;

import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import static com.ab.util.AbToastUtil.showToast;

public class RegistActivity extends AbActivity {
    MyApplication application;
    private static final int CODE_ING = 1;   //已发送，倒计时
    private static final int CODE_REPEAT = 2;  //重新发送
    private static final int SMSDDK_HANDLER = 3;  //短信回调
    private int TIME = 60;//倒计时60s
    private Button btnRegist;
    private Button btnGetCode;
    private EditText codeText;
    private String userPhone;
    private EventHandler eh;

    private TextView regORlogin;

    private int state=0;//0为注册，1为登录
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_regist);
        application= (MyApplication) abApplication;
        if (!application.IfFirstStart()&&MyApplication.user.isLoginUser()){
            startActivity(new Intent(RegistActivity.this,MainActivity.class));
            RegistActivity.this.finish();
        }
        btnRegist=(Button)findViewById(R.id.registBtn);
        btnGetCode=(Button)findViewById(R.id.button8);
        codeText=(EditText)findViewById(R.id.editText);
        regORlogin= (TextView) findViewById(R.id.regORlog);
        final EditText userPhoneText=(EditText)findViewById(R.id.userPhone);

        if (!application.IfFirstStart()){
            btnRegist.setText("登录");
            regORlogin.setText("去注册>");
            state=1;
        }

        MobSDK.init(RegistActivity.this, "1f6aa4d8bf8ac", "b4c9929b1c9ff71a8541dbcf1ab83401");
        eh=new EventHandler(){

            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                msg.what = SMSDDK_HANDLER;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调

        regORlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (state==0){
                    btnRegist.setText("登录");
                    regORlogin.setText("去注册>");
                    state=1;
                }else {
                    btnRegist.setText("下一步");
                    regORlogin.setText("已有账号？去登录>");
                    state=0;
                }
            }
        });


        btnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnGetCode.setClickable(false);
                userPhone=userPhoneText.getText().toString();
                SMSSDK.getVerificationCode("86", userPhone);
                new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        for (int i = 60; i > 0; i--)
                        {
                            handler.sendEmptyMessage(CODE_ING);
                            if (i <= 0)
                            {
                                break;
                            }
                            try
                            {
                                Thread.sleep(1000);
                            } catch (InterruptedException e)
                            {
                                e.printStackTrace();
                            }
                        }
                        TIME=60;
                        handler.sendEmptyMessage(CODE_REPEAT);
                    }
                }).start();

            }
        });

        btnRegist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SMSSDK.submitVerificationCode("86", userPhone, codeText.getText().toString());//对验证码进行验证->回调函
//                userPhone=userPhoneText.getText().toString();
//                Intent intent=new Intent(RegistActivity.this,RegistPassActivity.class);
//                intent.putExtra("userPhone",userPhone);
//                startActivity(intent);
            }
        });
        //application.setFirstStart(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case CODE_ING://已发送,倒计时
                    btnGetCode.setText("重新发送("+--TIME+"s)");
                    break;
                case CODE_REPEAT://重新发送
                    btnGetCode.setText("获取验证码");
                    btnGetCode.setClickable(true);
                    break;
                case SMSDDK_HANDLER:
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    //回调完成
                    if (result == SMSSDK.RESULT_COMPLETE)
                    {
                        //验证码验证成功
                        if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE)
                        {
                            showToast(RegistActivity.this,"验证成功");
                            if (state==0){//注册
//                                String url="http://192.168.191.1/Reading/InfoDoServlet?Action=register&UserID="+userPhone;
//                                UpdateUserToServer(url);
                                Intent intent=new Intent(RegistActivity.this,RegistPassActivity.class);
                                intent.putExtra("userPhone",userPhone);
                                startActivity(intent);
                            }else if (state==1){//登录
                                String url="http://192.168.191.1/Reading/InfoDoServlet?Action=login&UserID="+userPhone;
                                LoginServer(url);
                            }
                        }
                        //已发送验证码
                        else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE)
                        {
                            showToast(RegistActivity.this,"验证码已经发送");
                        } else
                        {
                            ((Throwable) data).printStackTrace();
                        }
                    }
                    if(result==SMSSDK.RESULT_ERROR)
                    {
                        showToast(RegistActivity.this,"验证失败");
                        try {
                            Throwable throwable = (Throwable) data;
                            throwable.printStackTrace();
                            JSONObject object=new JSONObject(throwable.getMessage());
                            String des=object.optString("detail");//错误描述
                            int status=object.optInt("status");//错误代码
                            if(status>0&&des!=null){
                                showToast(RegistActivity.this,des);
                                return;
                            }
                        }catch (Exception e){

                        }
                    }
                    break;
            }
        }
    };
//    private boolean ifAlreadyRegist=false;
//    public void JudgeUser(){
//        String url="http://192.168.191.1/Reading/InfoDoServlet?Action=login&UserID="+userPhone;
//        AbHttpUtil abHttpUtil=AbHttpUtil.getInstance(RegistActivity.this);
//        abHttpUtil.get(url, new AbStringHttpResponseListener() {
//            @Override
//            public void onSuccess(int i, String s) {
//                if (s.equals("false"))
//                    ifAlreadyRegist=true;
//            }
//
//            @Override
//            public void onStart() {
//            }
//
//            @Override
//            public void onFinish() {
//
//            }
//
//            @Override
//            public void onFailure(int i, String s, Throwable throwable) {
//            }
//        });
//    }
    public void LoginServer(String url){
        AbHttpUtil abHttpUtil=AbHttpUtil.getInstance(RegistActivity.this);
        abHttpUtil.get(url, new AbStringHttpResponseListener() {
            @Override
            public void onSuccess(int i, String s) {
                if (s.equals("true")){
                    AppUser user=new AppUser();
                    user.setUserID(userPhone);
                    user.setLoginUser(true);
                    application.setFirstStart(false);
                    application.updateLoginParams(user);
                    startActivity(new Intent(RegistActivity.this,MainActivity.class));
                    RegistActivity.this.finish();
                    //不能写在完成中，因为完成在有重定向的情况会提前结束
                    AbDialogUtil.removeDialog(RegistActivity.this);
                    SMSSDK.unregisterEventHandler(eh);
                }else {
                    showToast(RegistActivity.this,"登陆失败");
                    AbDialogUtil.removeDialog(RegistActivity.this);
                }
            }

            @Override
            public void onStart() {
                AbDialogUtil.showProgressDialog(RegistActivity.this,0,"正在请求...");
            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onFailure(int i, String s, Throwable throwable) {
                showToast(RegistActivity.this,"请求失败");
                AbDialogUtil.removeDialog(RegistActivity.this);
                AbToastUtil.showToast(RegistActivity.this,throwable.getMessage());
            }
        });
    }

}




